#include "ChatGrpcClient.h"
#include "ConfigMgr.h"
#include <sstream>
#include "const.h"

ChatGrpcClient::ChatGrpcClient()
{
    auto & cfg = ConfigMgr::GetInstance();

    //拿到服务器列表
    std::string server_list = cfg["PeerServer"]["Servers"];
    //对于服务器列表servers进行字符串切割，识别出每个chatserver的ip和port
    std::stringstream ss(server_list);

    std::vector<std::string> servers;
    std::string server;

    while(std::getline(ss,server,','))
    {
        servers.push_back(server);
    }

    
    for(const std::string & peerName: servers)
    {
        if(cfg[peerName]["Name"].empty()) continue;
        std::string host = cfg[peerName]["Host"];
        std::string port = cfg[peerName]["Port"];
        _pools[peerName] = std::make_unique<ChatConPool>(5, host, port);
    }
    
}


ChatGrpcClient::~ChatGrpcClient()
{

}


 AddFriendRsp ChatGrpcClient::NotifyAddFriend(std::string server_ip, const AddFriendReq &req)
 {
    
    AddFriendRsp rsp;
    rsp.set_error(ErrorCodes::Success);
    Defer defer([&rsp,&req](){
        rsp.set_applyuid(req.applyuid());
        rsp.set_touid(req.touid());
    });
    // 获取对端的连接
    auto iter = _pools.find(server_ip);
    if(iter == _pools.end())
    {
        rsp.set_error(ErrorCodes::RPCFailed);
        return rsp;
    }
   
    std::unique_ptr<ChatConPool>& conn = iter->second;
    std::unique_ptr<message::ChatService::Stub> stub = conn->GetConnection();
    // 利用RAII机制，确保连接在函数结束时归还连接池
    Defer defer2([&conn,&stub](){
        conn->ReturnConnection(std::move(stub));
    });
    // 构建上下文
    ClientContext context;
    // 调用RPC方法
    Status status = stub->NotifyAddFriend(&context, req, &rsp);
    if (!status.ok())
    {
        rsp.set_error(ErrorCodes::RPCFailed);
        return rsp;
    }


    return rsp;

 }

AuthFriendRsp ChatGrpcClient::NotifyAuthFriend(std::string server_ip, const AuthFriendReq &req)
{
    AuthFriendRsp rsp;

    return rsp;
}

TextChatMsgRsp ChatGrpcClient::NotifyTextChatMsg(std::string server_ip, const SendChatMsgReq &req)
{
    TextChatMsgRsp rsp;

    return rsp;
}

bool ChatGrpcClient::GetBaseInfo(std::string server_ip, std::shared_ptr<UserInfo> userinfo)
{
    return true;
}